use crate::errors::AppError;
use crate::models::{NewTodoItem, TodoItem, UpdateTodoItem};
use reqwest::{Client, Url};
use web_sys::window;
//use gloo::console;

fn get_base_url() -> Option<String> {
    let window = window()?;
    let document_url = window.document()?.url().ok()?;
    let href = document_url.as_str();

    let base_url = href.splitn(4, '/').collect::<Vec<&str>>()[0..3].join("/");

    Some(base_url)
}

// ApiClient结构体
pub struct ApiClient {
    client: Client,
    base_url: Url,
}

impl ApiClient {
    pub fn new() -> Result<Self, AppError> {
        let client = Client::new();
        let base_url = Url::parse(&get_base_url().expect("获取base_url出错"))?;
        Ok(Self { client, base_url })
    }

    pub async fn get_todos(&self, owner_key: &str) -> Result<Vec<TodoItem>, AppError> {
        let url = self
            .base_url
            .join(&format!("/api/todo/list/{}", owner_key))?;
        let resp = self.client.get(url).send().await?;
        let todos: Vec<TodoItem> = resp.json().await?;
        Ok(todos)
    }

    pub async fn get_todos_mock(&self, owner_key: &str) -> Result<Vec<TodoItem>, AppError> {
        let todo_items = vec![
            TodoItem {
                id: "1".to_string(),
                owner_key: "owner1".to_string(),
                title: "第一个待办事项".to_string(),
                description: Some("这是第一个待办事项的描述".to_string()),
                finished: false,
                created_at: "2023-10-23T10:00:00Z".to_string(),
                updated_at: "2023-10-23T10:00:00Z".to_string(),
            },
            TodoItem {
                id: "2".to_string(),
                owner_key: "owner2".to_string(),
                title: "第二个待办事项".to_string(),
                description: None, // 也可以设置为 Some("这是第二个待办事项的描述".to_string()), 如果你想提供一个描述
                finished: false,
                created_at: "2023-10-23T10:30:00Z".to_string(),
                updated_at: "2023-10-23T10:30:00Z".to_string(),
            },
        ];
        Ok(todo_items)
    }

    pub async fn new_todo(&self, todo: &NewTodoItem) -> Result<String, AppError> {
        let url = self.base_url.join("/api/todo")?;
        let resp = self.client.post(url).json(todo).send().await?;
        Ok(resp.text().await?)
    }

    pub async fn update_todo(&self, todo: &UpdateTodoItem) -> Result<(), AppError> {
        let url = self.base_url.join("/api/todo")?;
        let _ = self.client.put(url).json(todo).send().await?;
        Ok(())
    }
}
